package myservlet;

import com.dzb.util.GraphicHelper;
import com.dzb.util.JdbcHelper;
import myclass.Customers;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

@WebServlet("/employee/*")
public class EmployeeServlet extends HttpServlet {
    private String location="F:/Travel_photo";
    private JdbcHelper helper=new JdbcHelper();
    private Customers customers=new Customers();
    private static String encoding="UTF-8";

    /**
     * 设置字符编码集
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void setEncoding(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        this.encoding=request.getParameter("encoding");
    }

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String uri=request.getRequestURI();   //uri统一资源标识符

        int firstSlash=uri.indexOf("/");
        int lastSlash=uri.lastIndexOf("/");
        int length=uri.length();
        if(firstSlash!=lastSlash&&lastSlash!=length-1){
           String uriSuffix=uri.substring(lastSlash+1);
           switch(uriSuffix){
               case "sign-login":
                   signLogin(request,response);break;
               case "sign-register":
                   signRegister(request,response);break;
               case "sign-find":
                   signFind(request,response);break;
               case "sign-identify":
                   signIdentify(request,response);break;
           }
        }

    }

    /**
     * 登录验证，将登录表单发送的内容和数据库客户表Customers进行匹对，成功匹配就跳转到主界面，失败则跳转回登录界面
     * @param req  请求
     * @param res  响应
     * @throws ServletException
     * @throws IOException
     */
    public void signLogin(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        req.setCharacterEncoding(this.encoding);
        res.setContentType("text/html;charset="+this.encoding);

        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;
        String name=request.getParameter("username");
        String pas=request.getParameter("pas");
        String verifyCode=request.getParameter("verifyCode");
        HttpSession session=request.getSession();
        Object identify=session.getAttribute("identify");


        List<Map<String,Object>> list=helper.Query("select password from Customers where username=?",name);
        Iterator<Map<String,Object>> iter=list.iterator();

        if(list!=null&&list.size()>0){


            Map<String,Object>map=iter.next();
            Set<Map.Entry<String,Object>> eset=map.entrySet();
            for(Map.Entry<String,Object>e:eset){
                if(pas.equals(e.getValue())&&verifyCode.equals(identify)){
                    request.setAttribute(name,pas);
                    response.getWriter().println("<h3 align='center'>登录成功，3秒后跳转主页面</h3>");
                    response.setHeader("refresh","3;url=/html/index.html");
                }
            }
        }else{
            response.getWriter().println("<h3 align='center'>登录失败，3秒后跳转回登录页面</h3>");
            response.setHeader("refresh","3;url=/html/login.html");
        }
    }

    /**
     * 注册录入，将客户信息录入进数据库同时将这些信息封装到Customers类中
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    public void signRegister(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;

        request.setCharacterEncoding(this.encoding);
        response.setCharacterEncoding(this.encoding);
        response.setContentType("text/html;charset="+this.encoding);
        String username=request.getParameter("username");
        String password=request.getParameter("pas");
        String sex=request.getParameter("sex");
        String telephone=request.getParameter("tele");
        int id=helper.Insert("insert into Customers(Username,Password,Sex,Telephone) values(?,?,?,?)",username,password,sex,telephone);

        if(id>0){
            customers.setId(id);
            customers.setUsername(username);
            customers.setPassword(password);
            customers.setSex(sex);
            customers.setTelephone(telephone);

            HttpSession session=request.getSession();
            session.setAttribute("customer",customers);

            response.getWriter().println("<h3 align='center'>注册成功，即将返回登录界面</h3>");
            response.setHeader("refresh","3;url=/html/login.html");

        }
    }

    /**
     * 寻找图片位置，出于对安全的考虑，将图片放于盘符下某文件夹下
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void signFind(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        String photo1=request.getParameter("photo");
        File dir=new File(location);
        File[] files=dir.listFiles();


        OutputStream out=response.getOutputStream();
        for(File f:files){
            String filename=f.getName();
            if(filename.equals(photo1)){
                Path path=Paths.get(location,photo1);

                if(Files.exists(path)&&Files.isRegularFile(path)){
                    response.setContentType("image/jpeg");
                    Files.copy(path,out);
                }
            }

        }
    }

    /**
     * 显示验证码
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */
    public void signIdentify(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)res;

        String name=GraphicHelper.create( 4 , false , 180 , 50 , new FileOutputStream( "F:/Travel_photo/logo.jpg" )  , 30 );
        HttpSession session=request.getSession();
        session.setAttribute("identify",name);
        System.out.println(session.getAttribute("identify"));

        OutputStream out=response.getOutputStream();

        Path path=Paths.get("F:/Travel_photo/logo.jpg");

        if(Files.exists(path)&&Files.isRegularFile(path)){
            response.setContentType("image/jpeg");
            Files.copy(path,out);

        }
    }
}
